const Router = require('koa-router')
const { check, catchError, generateOk } = require('../../lib/check')
const { searchAccountById, searchAccount } = require('../../model/accounts')
const { setArticle, getAllArticles, searchArticle, editArticle } = require('../../model/articles')

let article = new Router()

article.post('/changeStatus', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!data.id, 'Params_Lost')
    // check(!!data.lable, 'Params_Lost')
    // check(data.state !== undefined, 'Params_Lost')
    const findArticle = searchArticle(data.id)
    check(findArticle, 'Not_Article')
    editArticle({ ...findArticle, status: findArticle.status === 0 ? 1 : 0 })
    ctx.body = generateOk({ ...findArticle, status: findArticle.status === 0 ? 1 : 0 })
  } catch (e) {
    catchError(e, ctx)
  }
})

article.post('/get', async (ctx) => {
  try {
    const data = ctx.request.body
    const articles = getAllArticles()
    let newArticles = articles

    if (data.create_Ts === 'descend') {
      newArticles = newArticles.sort((a, b) => Number(b.create_Ts) - Number(a.create_Ts))
    } else {
      newArticles = newArticles.sort((a, b) => Number(a.create_Ts) - Number(b.create_Ts))
    }
    if (data.like === 'descend') {
      newArticles = newArticles.sort((a, b) => Number(b.like.length) - Number(a.like.length))
    } else {
      newArticles = newArticles.sort((a, b) => Number(a.like.length) - Number(b.like.length))
    }
    if (data.save === 'descend') {
      newArticles = newArticles.sort((a, b) => Number(b.save.length) - Number(a.save.length))
    } else {
      newArticles = newArticles.sort((a, b) => Number(a.save.length) - Number(b.save.length))
    }
    if (data.comments === 'descend') {
      newArticles = newArticles.sort((a, b) => Number(b.comments.length) - Number(a.comments.length))
    } else {
      newArticles = newArticles.sort((a, b) => Number(a.comments.length) - Number(b.comments.length))
    }
    if (!!data.author) {
      const findAccount = searchAccountById(data.author)
      check(findAccount, 'No_Such_Account')
      newArticles = newArticles.filter(item => item.author === data.author)
    }
    if (data.status !== undefined) {
      newArticles = newArticles.filter((item) => item.status === data.status)
    }
    if (data.title !== undefined) {
      newArticles = newArticles.filter((item) => item.title.includes(data.title))
    }
    if (data.tabs !== undefined) {
      newArticles = newArticles.filter((item) => item.tabs.find(tab => tab.lable.includes(data.tabs)) !== undefined)
    }
    const start = data.offset === undefined ? 0 : data.offset
    const size = data.limit === undefined ? 7 : data.limit
    const resData = newArticles.slice(start, start + size)
    ctx.body = generateOk({ data: resData, total: newArticles.length, length: resData.length })
  } catch (e) {
    catchError(e, ctx)
  }
})


module.exports = article